package http

import (
	"bytes"
	"io/ioutil"
	"net/http"
	"net/url"
	"time"
)

var (
	Application_json string = "application/json"
)

// Get请求
// @param url	请求url
// @return
func Get(url string) (string, error) {
	client := &http.Client{Timeout: time.Second * 10}
	resp, err := client.Get(url)
	if err != nil {
		return "", err
	}
	defer resp.Body.Close()
	body, _ := ioutil.ReadAll(resp.Body)
	return string(body), err
}

func PostForm(url string, params url.Values) (string, error) {
	//设置超时时间，防止长时间堵塞
	client := &http.Client{Timeout: time.Second * 10}
	resp, err := client.PostForm(url, params)
	if err != nil {
		return "", err
	}
	defer resp.Body.Close()
	body, _ := ioutil.ReadAll(resp.Body)
	return string(body), err
}

func PostJson(url string, json string) (string, error) {
	client := &http.Client{Timeout: time.Second * 10}
	resp, err := client.Post(url, Application_json, bytes.NewBuffer([]byte(json)))
	if err != nil {
		return "", err
	}
	defer resp.Body.Close()
	body, _ := ioutil.ReadAll(resp.Body)
	return string(body), err
}

func PostHeaderJson(url string, jsonBody string, header map[string]string) (string, error) {
	req, err := http.NewRequest("POST", url, bytes.NewBuffer([]byte(jsonBody)))
	if err != nil {
		return "", err
	}
	if len(header) > 0 {
		for key, value := range header {
			req.Header.Set(key, value)
		}
	}
	//设置超时时间，防止长时间堵塞
	client := &http.Client{Timeout: time.Second * 10}
	resp, err := client.Do(req)
	if err != nil {
		return "", err
	}
	defer resp.Body.Close()
	body, _ := ioutil.ReadAll(resp.Body)
	return string(body), err
}
